package com.rskj.cashbook.controller;

import com.rskj.cashbook.response.ResponseEntity;
import com.rskj.cashbook.service.AutoAccountingRuleService;
import com.rskj.cashbook.vo.AutoAccountingRuleTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 自动记账规则模板控制器
 * @author system
 */
@RestController
@RequestMapping("/auto-accounting/templates")
@CrossOrigin(origins = "*")
public class AutoAccountingTemplateController {
    
    @Autowired
    private AutoAccountingRuleService autoAccountingRuleService;
    
    /**
     * 获取所有模板
     */
    @GetMapping
    public ResponseEntity<List<AutoAccountingRuleTemplate>> getAllTemplates() {
        try {
            List<AutoAccountingRuleTemplate> templates = autoAccountingRuleService.getRuleTemplates();
            return ResponseEntity.ok(templates);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 获取所有模板（分页）
     */
    @GetMapping("/paged")
    public ResponseEntity<com.github.pagehelper.PageInfo<AutoAccountingRuleTemplate>> getAllTemplatesWithPagination(
            @RequestParam(defaultValue = "1") int pageNumber,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String keyword) {
        try {
            com.github.pagehelper.PageInfo<AutoAccountingRuleTemplate> result = autoAccountingRuleService.getTemplatesWithPageHelper(pageNumber, pageSize, category, keyword);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 根据分类获取模板
     */
    @GetMapping("/category/{category}")
    public ResponseEntity<List<AutoAccountingRuleTemplate>> getTemplatesByCategory(@PathVariable String category) {
        try {
            List<AutoAccountingRuleTemplate> allTemplates = autoAccountingRuleService.getRuleTemplates();
            List<AutoAccountingRuleTemplate> filteredTemplates = allTemplates.stream()
                    .filter(template -> category.equals(template.getCategory()))
                    .collect(java.util.stream.Collectors.toList());
            return ResponseEntity.ok(filteredTemplates);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 根据标签搜索模板
     */
    @GetMapping("/search")
    public ResponseEntity<List<AutoAccountingRuleTemplate>> searchTemplates(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category) {
        try {
            List<AutoAccountingRuleTemplate> allTemplates = autoAccountingRuleService.getRuleTemplates();
            List<AutoAccountingRuleTemplate> filteredTemplates = allTemplates.stream()
                    .filter(template -> {
                        boolean matchesKeyword = keyword == null || keyword.isEmpty() ||
                                template.getTemplateName().toLowerCase().contains(keyword.toLowerCase()) ||
                                template.getDescription().toLowerCase().contains(keyword.toLowerCase());
                        
                        boolean matchesCategory = category == null || category.isEmpty() ||
                                category.equals(template.getCategory());
                        
                        return matchesKeyword && matchesCategory;
                    })
                    .collect(java.util.stream.Collectors.toList());
            
            return ResponseEntity.ok(filteredTemplates);
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 根据模板创建规则
     */
    @PostMapping("/{templateId}/create-rule")
    public ResponseEntity<Map<String, Object>> createRuleFromTemplate(
            @PathVariable String templateId,
            @RequestBody Map<String, Object> customizations) {
        try {
            // 验证模板是否存在
            List<AutoAccountingRuleTemplate> allTemplates = autoAccountingRuleService.getRuleTemplates();
            boolean templateExists = allTemplates.stream()
                    .anyMatch(template -> templateId.equals(template.getId()));
            
            if (!templateExists) {
                return ResponseEntity.failGeneric("模板不存在");
            }
            
            // 创建规则
            var rule = autoAccountingRuleService.createRuleFromTemplate(templateId, customizations);
            
            Map<String, Object> result = new java.util.HashMap<>();
            result.put("rule", rule);
            result.put("templateId", templateId);
            result.put("message", "根据模板成功创建规则");
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 获取模板使用统计
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getTemplateStats() {
        try {
            List<AutoAccountingRuleTemplate> allTemplates = autoAccountingRuleService.getRuleTemplates();
            
            Map<String, Object> stats = new java.util.HashMap<>();
            
            // 按分类统计
            Map<String, Long> categoryStats = allTemplates.stream()
                    .collect(java.util.stream.Collectors.groupingBy(
                            template -> template.getCategory() != null ? template.getCategory() : "UNKNOWN",
                            java.util.stream.Collectors.counting()));
            
            stats.put("totalTemplates", allTemplates.size());
            stats.put("categoryStats", categoryStats);
            
            // 最受欢迎的模板（按使用次数排序）
            List<AutoAccountingRuleTemplate> popularTemplates = allTemplates.stream()
                    .sorted((t1, t2) -> Integer.compare(
                            t2.getUsageCount() != null ? t2.getUsageCount() : 0,
                            t1.getUsageCount() != null ? t1.getUsageCount() : 0))
                    .limit(5)
                    .collect(java.util.stream.Collectors.toList());
            
            stats.put("popularTemplates", popularTemplates);
            
            // 活跃模板数量
            long activeTemplates = allTemplates.stream()
                    .filter(template -> Boolean.TRUE.equals(template.getIsActive()))
                    .count();
            
            stats.put("activeTemplates", activeTemplates);
            stats.put("inactiveTemplates", allTemplates.size() - activeTemplates);
            
            return ResponseEntity.ok(stats);
            
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 获取模板详情
     */
    @GetMapping("/{templateId}")
    public ResponseEntity<AutoAccountingRuleTemplate> getTemplateById(@PathVariable String templateId) {
        try {
            List<AutoAccountingRuleTemplate> allTemplates = autoAccountingRuleService.getRuleTemplates();
            
            AutoAccountingRuleTemplate template = allTemplates.stream()
                    .filter(t -> templateId.equals(t.getId()))
                    .findFirst()
                    .orElse(null);
            
            if (template == null) {
                return ResponseEntity.failGeneric("模板不存在");
            }
            
            return ResponseEntity.ok(template);
            
        } catch (Exception e) {
            throw e;
        }
    }
    
    /**
     * 获取推荐模板
     */
    @GetMapping("/recommendations")
    public ResponseEntity<List<AutoAccountingRuleTemplate>> getRecommendedTemplates(
            @RequestParam(required = false) String userId) {
        try {
            List<AutoAccountingRuleTemplate> allTemplates = autoAccountingRuleService.getRuleTemplates();
            
            // 根据使用次数和分类推荐模板
            List<AutoAccountingRuleTemplate> recommendedTemplates = allTemplates.stream()
                    .filter(template -> Boolean.TRUE.equals(template.getIsActive()))
                    .sorted((t1, t2) -> {
                        // 优先推荐使用次数多的模板
                        int usageCompare = Integer.compare(
                                t2.getUsageCount() != null ? t2.getUsageCount() : 0,
                                t1.getUsageCount() != null ? t1.getUsageCount() : 0);
                        
                        if (usageCompare != 0) {
                            return usageCompare;
                        }
                        
                        // 其次按分类优先级排序
                        String[] priorityOrder = {"COMMON", "EXPENSE", "INCOME", "TRANSFER"};
                        int t1Priority = java.util.Arrays.asList(priorityOrder).indexOf(t1.getCategory());
                        int t2Priority = java.util.Arrays.asList(priorityOrder).indexOf(t2.getCategory());
                        
                        return Integer.compare(t1Priority, t2Priority);
                    })
                    .limit(10)
                    .collect(java.util.stream.Collectors.toList());
            
            return ResponseEntity.ok(recommendedTemplates);
            
        } catch (Exception e) {
            throw e;
        }
    }
}
